package cn.mumzone.pos.ui.widgets;

import android.content.Context;
import android.support.annotation.ColorInt;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.configure.PickerOptions;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.ISelectTimeCallback;
import com.bigkoo.pickerview.listener.OnTimeSelectChangeListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.BasePickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bigkoo.pickerview.view.WheelTime;
import com.contrarywind.view.WheelView;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

import cn.mumzone.pos.R;

/**
 * Created by qiuzhenhuan on 2019/8/5.
 */

public class PosTimePickerView extends BasePickerView implements View.OnClickListener {

    private WheelTime wheelTime; //自定义控件
    private static final String TAG_SUBMIT = "submit";
    private static final String TAG_CANCEL = "cancel";

    public PosTimePickerView(PickerOptions pickerOptions) {
        super(pickerOptions.context);
        mPickerOptions = pickerOptions;
        initView(pickerOptions.context);
    }

    private void initView(Context context) {
        setDialogOutSideCancelable();
        initViews();
        initAnim();

        if (mPickerOptions.customListener == null) {
            LayoutInflater.from(context).inflate(R.layout.dialog_time_picker, contentContainer);

            //顶部标题
            TextView tvTitle = (TextView) findViewById(com.bigkoo.pickerview.R.id.tvTitle);
            RelativeLayout rv_top_bar = (RelativeLayout) findViewById(com.bigkoo.pickerview.R.id.rv_topbar);

            //确定和取消按钮
            Button btnSubmit = (Button) findViewById(com.bigkoo.pickerview.R.id.btnSubmit);
            Button btnCancel = (Button) findViewById(com.bigkoo.pickerview.R.id.btnCancel);

            btnSubmit.setTag(TAG_SUBMIT);
            btnCancel.setTag(TAG_CANCEL);

            btnSubmit.setOnClickListener(this);
            btnCancel.setOnClickListener(this);

            //设置文字
            btnSubmit.setText(TextUtils.isEmpty(mPickerOptions.textContentConfirm) ? context.getResources().getString(com.bigkoo.pickerview.R.string.pickerview_submit) : mPickerOptions.textContentConfirm);
            btnCancel.setText(TextUtils.isEmpty(mPickerOptions.textContentCancel) ? context.getResources().getString(com.bigkoo.pickerview.R.string.pickerview_cancel) : mPickerOptions.textContentCancel);
            tvTitle.setText(TextUtils.isEmpty(mPickerOptions.textContentTitle) ? "" : mPickerOptions.textContentTitle);//默认为空

            //设置color
            btnSubmit.setTextColor(mPickerOptions.textColorConfirm);
            btnCancel.setTextColor(mPickerOptions.textColorCancel);
            tvTitle.setTextColor(mPickerOptions.textColorTitle);
            rv_top_bar.setBackgroundColor(mPickerOptions.bgColorTitle);

            //设置文字大小
            btnSubmit.setTextSize(mPickerOptions.textSizeSubmitCancel);
            btnCancel.setTextSize(mPickerOptions.textSizeSubmitCancel);
            tvTitle.setTextSize(mPickerOptions.textSizeTitle);

        } else {
            mPickerOptions.customListener.customLayout(LayoutInflater.from(context).inflate(mPickerOptions.layoutRes, contentContainer));
        }
        // 时间转轮 自定义控件
        LinearLayout timePickerView = (LinearLayout) findViewById(com.bigkoo.pickerview.R.id.timepicker);
        timePickerView.setBackgroundColor(mPickerOptions.bgColorWheel);

        initWheelTime(timePickerView);
    }

    private void initWheelTime(LinearLayout timePickerView) {
        wheelTime = new WheelTime(timePickerView, mPickerOptions.type, mPickerOptions.textGravity, mPickerOptions.textSizeContent);
        if (mPickerOptions.timeSelectChangeListener != null) {
            wheelTime.setSelectChangeCallback(new ISelectTimeCallback() {
                @Override
                public void onTimeSelectChanged() {
                    try {
                        Date date = WheelTime.dateFormat.parse(wheelTime.getTime());
                        mPickerOptions.timeSelectChangeListener.onTimeSelectChanged(date);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        wheelTime.setLunarMode(mPickerOptions.isLunarCalendar);

        if (mPickerOptions.startYear != 0 && mPickerOptions.endYear != 0
                && mPickerOptions.startYear <= mPickerOptions.endYear) {
            setRange();
        }

        //若手动设置了时间范围限制
        if (mPickerOptions.startDate != null && mPickerOptions.endDate != null) {
            if (mPickerOptions.startDate.getTimeInMillis() > mPickerOptions.endDate.getTimeInMillis()) {
                throw new IllegalArgumentException("startDate can't be later than endDate");
            } else {
                setRangDate();
            }
        } else if (mPickerOptions.startDate != null) {
            if (mPickerOptions.startDate.get(Calendar.YEAR) < 1900) {
                throw new IllegalArgumentException("The startDate can not as early as 1900");
            } else {
                setRangDate();
            }
        } else if (mPickerOptions.endDate != null) {
            if (mPickerOptions.endDate.get(Calendar.YEAR) > 2100) {
                throw new IllegalArgumentException("The endDate should not be later than 2100");
            } else {
                setRangDate();
            }
        } else {//没有设置时间范围限制，则会使用默认范围。
            setRangDate();
        }

        setTime();
        wheelTime.setLabels(mPickerOptions.label_year, mPickerOptions.label_month, mPickerOptions.label_day
                , mPickerOptions.label_hours, mPickerOptions.label_minutes, mPickerOptions.label_seconds);
        wheelTime.setTextXOffset(mPickerOptions.x_offset_year, mPickerOptions.x_offset_month, mPickerOptions.x_offset_day,
                mPickerOptions.x_offset_hours, mPickerOptions.x_offset_minutes, mPickerOptions.x_offset_seconds);

        setOutSideCancelable(mPickerOptions.cancelable);
        wheelTime.setCyclic(mPickerOptions.cyclic);
        wheelTime.setDividerColor(mPickerOptions.dividerColor);
        wheelTime.setDividerType(mPickerOptions.dividerType);
        wheelTime.setLineSpacingMultiplier(mPickerOptions.lineSpacingMultiplier);
        wheelTime.setTextColorOut(mPickerOptions.textColorOut);
        wheelTime.setTextColorCenter(mPickerOptions.textColorCenter);
        wheelTime.isCenterLabel(mPickerOptions.isCenterLabel);
    }


    /**
     * 设置默认时间
     */
    public void setDate(Calendar date) {
        mPickerOptions.date = date;
        setTime();
    }

    /**
     * 设置可以选择的时间范围, 要在setTime之前调用才有效果
     */
    private void setRange() {
        wheelTime.setStartYear(mPickerOptions.startYear);
        wheelTime.setEndYear(mPickerOptions.endYear);

    }

    /**
     * 设置可以选择的时间范围, 要在setTime之前调用才有效果
     */
    private void setRangDate() {
        wheelTime.setRangDate(mPickerOptions.startDate, mPickerOptions.endDate);
        initDefaultSelectedDate();
    }

    private void initDefaultSelectedDate() {
        //如果手动设置了时间范围
        if (mPickerOptions.startDate != null && mPickerOptions.endDate != null) {
            //若默认时间未设置，或者设置的默认时间越界了，则设置默认选中时间为开始时间。
            if (mPickerOptions.date == null || mPickerOptions.date.getTimeInMillis() < mPickerOptions.startDate.getTimeInMillis()
                    || mPickerOptions.date.getTimeInMillis() > mPickerOptions.endDate.getTimeInMillis()) {
                mPickerOptions.date = mPickerOptions.startDate;
            }
        } else if (mPickerOptions.startDate != null) {
            //没有设置默认选中时间,那就拿开始时间当默认时间
            mPickerOptions.date = mPickerOptions.startDate;
        } else if (mPickerOptions.endDate != null) {
            mPickerOptions.date = mPickerOptions.endDate;
        }
    }

    /**
     * 设置选中时间,默认选中当前时间
     */
    private void setTime() {
        int year, month, day, hours, minute, seconds;
        Calendar calendar = Calendar.getInstance();

        if (mPickerOptions.date == null) {
            calendar.setTimeInMillis(System.currentTimeMillis());
            year = calendar.get(Calendar.YEAR);
            month = calendar.get(Calendar.MONTH);
            day = calendar.get(Calendar.DAY_OF_MONTH);
            hours = calendar.get(Calendar.HOUR_OF_DAY);
            minute = calendar.get(Calendar.MINUTE);
            seconds = calendar.get(Calendar.SECOND);
        } else {
            year = mPickerOptions.date.get(Calendar.YEAR);
            month = mPickerOptions.date.get(Calendar.MONTH);
            day = mPickerOptions.date.get(Calendar.DAY_OF_MONTH);
            hours = mPickerOptions.date.get(Calendar.HOUR_OF_DAY);
            minute = mPickerOptions.date.get(Calendar.MINUTE);
            seconds = mPickerOptions.date.get(Calendar.SECOND);
        }

        wheelTime.setPicker(year, month, day, hours, minute, seconds);
    }


    @Override
    public void onClick(View v) {
        String tag = (String) v.getTag();
        if (tag.equals(TAG_SUBMIT)) {
            returnData();
        } else if (tag.equals(TAG_CANCEL)) {
            if (mPickerOptions.cancelListener != null) {
                mPickerOptions.cancelListener.onClick(v);
            }
        }
        dismiss();
    }

    public void returnData() {
        if (mPickerOptions.timeSelectListener != null) {
            try {
                Date date = WheelTime.dateFormat.parse(wheelTime.getTime());
                mPickerOptions.timeSelectListener.onTimeSelect(date, clickView);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 动态设置标题
     *
     * @param text 标题文本内容
     */
    public void setTitleText(String text) {
        TextView tvTitle = (TextView) findViewById(com.bigkoo.pickerview.R.id.tvTitle);
        if (tvTitle != null) {
            tvTitle.setText(text);
        }
    }

    @Override
    public boolean isDialog() {
        return mPickerOptions.isDialog;
    }


    public static class PosTimePickerBuilder {

        private PickerOptions mPickerOptions;

        //Required
        public PosTimePickerBuilder(Context context, OnTimeSelectListener listener) {
            mPickerOptions = new PickerOptions(PickerOptions.TYPE_PICKER_TIME);
            mPickerOptions.context = context;
            mPickerOptions.timeSelectListener = listener;
        }

        //Option
        public PosTimePickerBuilder setGravity(int gravity) {
            mPickerOptions.textGravity = gravity;
            return this;
        }

        public PosTimePickerBuilder addOnCancelClickListener(View.OnClickListener cancelListener) {
            mPickerOptions.cancelListener = cancelListener;
            return this;
        }

        /**
         * new boolean[]{true, true, true, false, false, false}
         * control the "year","month","day","hours","minutes","seconds " display or hide.
         * 分别控制“年”“月”“日”“时”“分”“秒”的显示或隐藏。
         *
         * @param type 布尔型数组，长度需要设置为6。
         * @return PosTimePickerBuilder
         */
        public PosTimePickerBuilder setType(boolean[] type) {
            mPickerOptions.type = type;
            return this;
        }

        public PosTimePickerBuilder setSubmitText(String textContentConfirm) {
            mPickerOptions.textContentConfirm = textContentConfirm;
            return this;
        }

        public PosTimePickerBuilder isDialog(boolean isDialog) {
            mPickerOptions.isDialog = isDialog;
            return this;
        }

        public PosTimePickerBuilder setCancelText(String textContentCancel) {
            mPickerOptions.textContentCancel = textContentCancel;
            return this;
        }

        public PosTimePickerBuilder setTitleText(String textContentTitle) {
            mPickerOptions.textContentTitle = textContentTitle;
            return this;
        }

        public PosTimePickerBuilder setSubmitColor(int textColorConfirm) {
            mPickerOptions.textColorConfirm = textColorConfirm;
            return this;
        }

        public PosTimePickerBuilder setCancelColor(int textColorCancel) {
            mPickerOptions.textColorCancel = textColorCancel;
            return this;
        }

        /**
         * ViewGroup 类型的容器
         *
         * @param decorView 选择器会被添加到此容器中
         * @return PosTimePickerBuilder
         */
        public PosTimePickerBuilder setDecorView(ViewGroup decorView) {
            mPickerOptions.decorView = decorView;
            return this;
        }

        public PosTimePickerBuilder setBgColor(int bgColorWheel) {
            mPickerOptions.bgColorWheel = bgColorWheel;
            return this;
        }

        public PosTimePickerBuilder setTitleBgColor(int bgColorTitle) {
            mPickerOptions.bgColorTitle = bgColorTitle;
            return this;
        }

        public PosTimePickerBuilder setTitleColor(int textColorTitle) {
            mPickerOptions.textColorTitle = textColorTitle;
            return this;
        }

        public PosTimePickerBuilder setSubCalSize(int textSizeSubmitCancel) {
            mPickerOptions.textSizeSubmitCancel = textSizeSubmitCancel;
            return this;
        }

        public PosTimePickerBuilder setTitleSize(int textSizeTitle) {
            mPickerOptions.textSizeTitle = textSizeTitle;
            return this;
        }

        public PosTimePickerBuilder setContentTextSize(int textSizeContent) {
            mPickerOptions.textSizeContent = textSizeContent;
            return this;
        }

        /**
         * 因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
         *
         * @param date
         * @return PosTimePickerBuilder
         */
        public PosTimePickerBuilder setDate(Calendar date) {
            mPickerOptions.date = date;
            return this;
        }

        public PosTimePickerBuilder setLayoutRes(int res, CustomListener customListener) {
            mPickerOptions.layoutRes = res;
            mPickerOptions.customListener = customListener;
            return this;
        }


        /**
         * 设置起始时间
         * 因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
         */

        public PosTimePickerBuilder setRangDate(Calendar startDate, Calendar endDate) {
            mPickerOptions.startDate = startDate;
            mPickerOptions.endDate = endDate;
            return this;
        }


        /**
         * 设置间距倍数,但是只能在1.0-4.0f之间
         *
         * @param lineSpacingMultiplier
         */
        public PosTimePickerBuilder setLineSpacingMultiplier(float lineSpacingMultiplier) {
            mPickerOptions.lineSpacingMultiplier = lineSpacingMultiplier;
            return this;
        }

        /**
         * 设置分割线的颜色
         *
         * @param dividerColor
         */

        public PosTimePickerBuilder setDividerColor(@ColorInt int dividerColor) {
            mPickerOptions.dividerColor = dividerColor;
            return this;
        }

        /**
         * 设置分割线的类型
         *
         * @param dividerType
         */
        public PosTimePickerBuilder setDividerType(WheelView.DividerType dividerType) {
            mPickerOptions.dividerType = dividerType;
            return this;
        }

        /**
         * {@link #setOutSideColor} instead.
         *
         * @param backgroundId color resId.
         */
        @Deprecated
        public PosTimePickerBuilder setBackgroundId(int backgroundId) {
            mPickerOptions.outSideColor = backgroundId;
            return this;
        }

        /**
         * 显示时的外部背景色颜色,默认是灰色
         *
         * @param outSideColor
         */
        public PosTimePickerBuilder setOutSideColor(@ColorInt int outSideColor) {
            mPickerOptions.outSideColor = outSideColor;
            return this;
        }

        /**
         * 设置分割线之间的文字的颜色
         *
         * @param textColorCenter
         */
        public PosTimePickerBuilder setTextColorCenter(@ColorInt int textColorCenter) {
            mPickerOptions.textColorCenter = textColorCenter;
            return this;
        }

        /**
         * 设置分割线以外文字的颜色
         *
         * @param textColorOut
         */
        public PosTimePickerBuilder setTextColorOut(@ColorInt int textColorOut) {
            mPickerOptions.textColorOut = textColorOut;
            return this;
        }

        public PosTimePickerBuilder isCyclic(boolean cyclic) {
            mPickerOptions.cyclic = cyclic;
            return this;
        }

        public PosTimePickerBuilder setOutSideCancelable(boolean cancelable) {
            mPickerOptions.cancelable = cancelable;
            return this;
        }

        public PosTimePickerBuilder setLunarCalendar(boolean lunarCalendar) {
            mPickerOptions.isLunarCalendar = lunarCalendar;
            return this;
        }


        public PosTimePickerBuilder setLabel(String label_year, String label_month, String label_day, String label_hours, String label_mins, String label_seconds) {
            mPickerOptions.label_year = label_year;
            mPickerOptions.label_month = label_month;
            mPickerOptions.label_day = label_day;
            mPickerOptions.label_hours = label_hours;
            mPickerOptions.label_minutes = label_mins;
            mPickerOptions.label_seconds = label_seconds;
            return this;
        }

        /**
         * 设置X轴倾斜角度[ -90 , 90°]
         *
         * @param x_offset_year    年
         * @param x_offset_month   月
         * @param x_offset_day     日
         * @param x_offset_hours   时
         * @param x_offset_minutes 分
         * @param x_offset_seconds 秒
         * @return
         */
        public PosTimePickerBuilder setTextXOffset(int x_offset_year, int x_offset_month, int x_offset_day,
                                                   int x_offset_hours, int x_offset_minutes, int x_offset_seconds) {
            mPickerOptions.x_offset_year = x_offset_year;
            mPickerOptions.x_offset_month = x_offset_month;
            mPickerOptions.x_offset_day = x_offset_day;
            mPickerOptions.x_offset_hours = x_offset_hours;
            mPickerOptions.x_offset_minutes = x_offset_minutes;
            mPickerOptions.x_offset_seconds = x_offset_seconds;
            return this;
        }

        public PosTimePickerBuilder isCenterLabel(boolean isCenterLabel) {
            mPickerOptions.isCenterLabel = isCenterLabel;
            return this;
        }

        /**
         * @param listener 切换item项滚动停止时，实时回调监听。
         * @return
         */
        public PosTimePickerBuilder setTimeSelectChangeListener(OnTimeSelectChangeListener listener) {
            mPickerOptions.timeSelectChangeListener = listener;
            return this;
        }

        public PosTimePickerView build() {
            return new PosTimePickerView(mPickerOptions);
        }


    }
}
